<?php
/**
 * @Author: wonli <wonli@live.com>
 */
namespace modules\gwbn;

use Cross\MVC\Module;
use Exception;

class AdminModule extends Module
{
    /**
     * 管理员表
     *
     * @var string
     */
    protected $t_admin = 'gwbn_admin';

    /**
     * 登录验证
     *
     * @param string $username
     * @param string $password
     * @param string $code_location
     * @param string $code_value
     * @return array|string
     */
    function checkAdmin($username, $password/*, $code_location = '', $code_value = ''*/)
    {
        $SEC = new SecurityModule;
        try {
            $userinfo = $this->link->get($this->t_admin, '*', array('name' => $username));
        } catch (Exception $e) {
            return $this->result(100006);
        }

        if ($userinfo ['t'] != 1) {
            return $this->result(100001);
        }

        if ($userinfo && !empty($userinfo ["password"])) {
            if ($userinfo ['security'] == 0){
                $user_password = sha1(strtoupper($username) . ":" . strtoupper($password));
            }
            else{
                $user_password = sha1(md5($password));
            }

            $is_bind = $SEC->checkbind($username);

            /*if ($is_bind) {
                if (empty($code_location) || empty($code_value)) {
                    return $this->result(100004);
                }

                $verify_right = $SEC->verifyCode($username, $code_location, $code_value);
                if (!$verify_right) {
                    return $this->result(100005);
                }
            }*/

            if ($user_password === $userinfo ["password"]) {

                //姓名
                $_SESSION['uname'] = $userinfo ["uname"];

                //头像
                $_SESSION['avatars'] = $userinfo ["avatars"];

                switch($userinfo ["rid"]){

                    case '0':
                        $_SESSION['l'] = "超级管理员";
                        break;
                    case '1':
                        $_SESSION['l'] = "站长";
                        break;
                    case '2':
                        $_SESSION['l'] = "销售员";
                        break;
                    case '3':
                        $_SESSION['l'] = "管理员";
                        break;
                    case '4':
                        $_SESSION['l'] = "后勤统计";
                        break;

                    default:
                        $_SESSION['l'] = "";
                        break;
                }

                //uid
                $_SESSION['uid'] = $userinfo ["id"];

                //全局管理员判断函数
                $_SESSION['ADMIN'] = $userinfo ["rid"] == "0" ? "1" : "0";

                /**
                 * 记录登录信息
                 */

                //获取登录信息
                $Browser = $this->GetBrowser(); //获得访客浏览器类型
                $Langues = $this->GetLang();  //获得访客浏览器语言
                $Os = $this->GetOs();   //获取访客操作系统
                $ip = $this->Getip();   //获得访客真实ip
                $lip = $this->get_onlineip();   //获得本地真实IP
                $addr = $this->Getaddress($ip); //参数 $ip 是可选的，默认返回一个二维数组包含当前访客所在地的相关信息
                //echo "使用".$Browser."浏览器，语言：".$Langues."，操作系统：".$Os."，IP地址：".$ip."，真实IP地址：".$lip."，位于：".$addr[0][0].$addr[0][1].$addr[0][2];

                $type = $this->isMobile() ? 'mobile' : 'pc';

                //登录信息组装
                $login_info = $this->link->add('gwbn_admin_login_log',array(

                    //帐号ID
                    'aid' => $_SESSION['uid'],

                    //姓名
                    'name' => $_SESSION['uname'],

                    //登录时间
                    'time' => date('Y-m-d H:i:s'),

                    //登录IP
                    'ip' => $ip,

                    //登录设备类别
                    $type => $Os,

                    //浏览器
                    'browser' => $Browser,
                ));

                //登录信息写进数据库
                if ($login_info){}

                return $this->result(1);
            }
            return $this->result(100003);
        }

        return $this->result(100002);
    }

    /**
     * 管理员列表
     */
    function getUserList()
    {
        return $this->link->getAll($this->t_admin, "*");
    }

    /**
     * 新增加管理员
     *
     * @param $data
     * @return bool
     */
    function addAdmin($data)
    {
        if (empty($data['name']) || empty($data['password'])) {
            return false;
        }

        foreach ($data as $k => & $d) {
            if (empty($d)) {
                unset($data[$k]);
            }

            if ($k === 'password') {
                $d = sha1(md5($data ['password']));
            }
        }

        $this->link->add($this->t_admin, $data);
        return true;
    }

    /**
     * 根据condition查询管理员信息
     *
     * @param $condition
     * @return mixed
     */
    function getAdminInfo($condition)
    {
        return $this->link->get($this->t_admin, '*', $condition);
    }

    /**
     * 删除用户
     *
     * @param $condition
     * @return mixed
     */
    function del($condition)
    {
        return $this->link->del($this->t_admin, $condition);
    }

    /**
     * 更新管理员列表
     *
     * @param $data
     * @param $condition
     * @return array|string
     */
    function update($data, $condition)
    {
        $admin_info = $this->link->get($this->t_admin, '*', $condition);

        if (!$admin_info) {
            return $this->result(100025);
        }

        //更新密码
        if ($admin_info ['password'] !== $data['password']) {
            $data ['password'] = sha1(md5($data ['password']));
        }

        $this->link->update($this->t_admin, $data, $condition);
        return $this->result(1);
    }

    /**
     * 获取访问者信息
     */

    ////获得访客浏览器类型
    function GetBrowser(){
        if(!empty($_SERVER['HTTP_USER_AGENT'])){
            $br = $_SERVER['HTTP_USER_AGENT'];
            if (preg_match('/MSIE/i',$br)) {
                $br = 'MSIE';
            }elseif (preg_match('/Firefox/i',$br)) {
                $br = 'Firefox';
            }elseif (preg_match('/Chrome/i',$br)) {
                $br = 'Chrome';
            }elseif (preg_match('/Safari/i',$br)) {
                $br = 'Safari';
            }elseif (preg_match('/Opera/i',$br)) {
                $br = 'Opera';
            }else {
                $br = 'Other';
            }
            return $br;
        }else{return "获取浏览器信息失败！";}
    }

    ////获得访客浏览器语言
    function GetLang(){
        if(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
            $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
            $lang = substr($lang,0,5);
            if(preg_match("/zh-cn/i",$lang)){
                $lang = "简体中文";
            }elseif(preg_match("/zh/i",$lang)){
                $lang = "繁体中文";
            }else{
                $lang = "English";
            }
            return $lang;

        }else{return "获取浏览器语言失败！";}
    }

    ////获取访客操作系统
    function GetOs(){
        if(!empty($_SERVER['HTTP_USER_AGENT'])){
            $OS = $_SERVER['HTTP_USER_AGENT'];
            if (preg_match('/win/i',$OS)) {
                $OS = 'Windows';
            }elseif (preg_match('/mac/i',$OS)) {
                $OS = 'MAC';
            }elseif (preg_match('/linux/i',$OS)) {
                $OS = 'Linux';
            }elseif (preg_match('/unix/i',$OS)) {
                $OS = 'Unix';
            }elseif (preg_match('/bsd/i',$OS)) {
                $OS = 'BSD';
            }else {
                $OS = 'Other';
            }
            return $OS;
        }else{return "获取访客操作系统信息失败！";}
    }

    ////获得访客真实ip
    function Getip(){
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //获取代理ip
            $ips = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
        }
        if($ip){
            $ips = array_unshift($ips,$ip);
        }
        $count = count($ips);
        for($i=0;$i<$count;$i++){
            if(!preg_match("/^(10|172\.16|192\.168)\./i",$ips[$i])){//排除局域网ip
                $ip = $ips[$i];
                break;
            }
        }
        $tip = $ip ? $ip : $_SERVER['REMOTE_ADDR'];
        if($tip=="127.0.0.1"){ //获得本地真实IP
            return $this->get_onlineip();
        }else{
            return $tip;
        }
    }

    ////获得本地真实IP
    function get_onlineip() {
        $mip = file_get_contents("http://www.ip138.com/ip2city.asp");
        if($mip){
            preg_match("/\[.*\]/",$mip,$sip);
            $p = array("/\[/","/\]/");
            return preg_replace($p,"",$sip[0]);
        }else{return "获取本地IP失败！";}
    }

    ////根据ip获得访客所在地地名
    function Getaddress($ip=''){
        if(empty($ip)){
            $ip = $this->Getip();
        }
        $ipadd = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=".$ip);//根据新浪api接口获取
        if($ipadd){
            $charset = iconv("gbk","utf-8",$ipadd);
            preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$charset,$ipadds);
            return $ipadds;   //返回一个二维数组
        }else{return "addree is none";}
    }

    function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }

}

